package com.qf.channelPipeline;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @Description:
 * @Author: xbb
 * @Date:2020/4/20
 */
public class ClientDemo {
    public static void main(String[] args) {
        try {
            //1.创建一个线程池
            EventLoopGroup eventExecutors = new NioEventLoopGroup();

            //创建一个引导类
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors);    //客户端这边用多线程模型处理
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new SimpleChannelInboundHandler<StringDecoder>() {
                @Override
                protected void channelRead0(ChannelHandlerContext channelHandlerContext, StringDecoder stringDecoder) throws Exception {
                }
            });
            ChannelFuture channelFuture = bootstrap.connect("localhost", 8080);
            channelFuture.sync();
            System.out.println("客户端连接成功");

            Scanner scanner = new Scanner(System.in);
            while (true){
                //创建一个ByteBuf对象
                ByteBuf byteBuf = Unpooled.buffer(1024*10);
                String next = scanner.next();
                byteBuf.writeBytes(next.getBytes("utf-8"));
                channelFuture.channel().writeAndFlush(byteBuf); //异步的操作
                System.out.println("客户端写入完成");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
